import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pp_uikit/pp_group/pp_group_util.dart';
import 'package:pp_uikit/theme/pp_group_theme.dart';

///
/// 文本输入型录入项
///
/// 包括"标题"、"必填项提示"、"文本输入框"等元素
///
// ignore: must_be_immutable
class PPGroupInput extends StatefulWidget {
  /// 录入项标题
  final String title;

  /// 输入框的初始值，默认为""
  final String contentText;

  /// 录入项是否为必填项（展示*图标） 默认为 false 不必填
  final bool isRequire;

  /// 录入项 是否可编辑
  final bool isEdit;

  /// 提示文案
  final String hint;

  /// 输入内容类型
  final TextInputType inputType;

  /// 是否自动获取焦点
  bool autofocus;

  /// 是否密码
  final bool obscureText;

  /// 输入字符数上限
  final int? maxLength;

  /// 指定对输入数据的格式化要求
  final List<TextInputFormatter>? inputFormatters;

  /// 输入变化回调
  final ValueChanged<String>? onChanged;

  /// 点击确定后的回调
  final ValueChanged<String>? onSubmitted;

  /// 用于对 TextField  更精细的控制，若传入该字段，[contentText] 参数将失效，可使用 TextEditingController.text 进行赋值。
  final TextEditingController? controller;

  final FocusNode? focusNode;

  /// 背景色
  final Color? backgroundColor;

  /// 自定义右边Widget
  final Widget? rightWidget;

  /// form配置
  PPGroupTheme? themeData;

  PPGroupInput({
    Key? key,
    this.title = "",
    this.contentText = "",
    this.isEdit = true,
    this.isRequire = false,
    this.hint = "请输入",
    this.maxLength,
    this.autofocus = false,
    this.obscureText = false,
    this.inputType = TextInputType.text,
    this.inputFormatters,
    this.onChanged,
    this.onSubmitted,
    this.controller,
    this.focusNode,
    this.backgroundColor,
    this.rightWidget,
    this.themeData,
  }) : super(key: key) {
    themeData ??= PPGroupTheme();
  }

  @override
  State<StatefulWidget> createState() {
    return PPGroupInputState();
  }
}

class PPGroupInputState extends State<PPGroupInput> {
  late TextEditingController _controller;
  late FocusNode _focusNode;
  @override
  void initState() {
    String textData = widget.contentText;
    if (widget.maxLength != null &&
        widget.contentText.runes.length > widget.maxLength!) {
      var sRunes = textData.runes;
      textData = String.fromCharCodes(sRunes, 0, widget.maxLength);
    }
    var tmpController = widget.controller;
    if (tmpController == null) {
      if (textData.isNotEmpty) {
        tmpController = TextEditingController.fromValue(TextEditingValue(
            text: textData,
            selection: TextSelection.fromPosition(TextPosition(
                affinity: TextAffinity.downstream, offset: textData.length))));
      } else {
        tmpController = TextEditingController();
      }
    }
    _controller = tmpController;

    var tmpFocusNode = widget.focusNode;
    if (tmpFocusNode == null) {
      _focusNode = FocusNode();
    } else {
      _focusNode = tmpFocusNode;
    }

    // 监听焦点变化，并在焦点变为focused时将光标移动到最右边。
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        _controller.selection =
            TextSelection.collapsed(offset: _controller.text.length);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: widget.themeData!.backgroundColor,
      padding: widget.themeData?.groupPadding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          ConstrainedBox(
            constraints: const BoxConstraints(
              minHeight: 40,
            ),
            child: Row(
              children: <Widget>[
                // 必填项符号
                PPGroupUtil.buildRequireWidget(widget.isRequire),

                // 主标题
                PPGroupUtil.buildTitleWidget(widget.title),
                Expanded(
                  child: TextField(
                    autofocus: widget.autofocus,
                    keyboardType: widget.inputType,
                    enabled: widget.isEdit,
                    maxLines: 1,
                    maxLength: widget.maxLength,
                    obscureText: widget.obscureText,
                    style: PPGroupUtil.getEditTextStyle(widget.isEdit),
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintStyle: widget.themeData?.hintTextStyle,
                      hintText: widget.hint,
                      counterText: "",
                      contentPadding:
                          widget.themeData?.textFieldCcontentPadding,
                      isDense: true,
                      enabledBorder: const UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.transparent)),
                      focusedBorder: const UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.transparent)),
                    ),
                    textAlign: TextAlign.end,
                    controller: _controller,
                    focusNode: _focusNode,
                    inputFormatters: widget.inputFormatters,
                    onChanged: widget.onChanged,
                    onSubmitted: widget.onSubmitted,
                  ),
                ),
                if (widget.rightWidget != null) widget.rightWidget!,
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();

    // 如果controller由外部创建不需要销毁, 若由内部创建则需要销毁
    if (widget.controller == null) {
      _controller.dispose();
    }
    if (widget.focusNode == null) {
      _focusNode.dispose();
    }
  }
}
